package cn.schoolwow.flow.monitor.module.business.flowRecord.flow;

import cn.schoolwow.ams.domain.option.QuickAMSOption;
import cn.schoolwow.flow.monitor.domain.FlowMonitorOption;
import cn.schoolwow.flow.monitor.domain.FlowRecordable;
import cn.schoolwow.flow.monitor.module.business.flowRecord.domain.FlowRecordContext;
import cn.schoolwow.quickflow.domain.FlowContext;
import cn.schoolwow.quickflow.flow.BusinessFlow;
import cn.schoolwow.util.domain.query.queryPackage.QueryPackage;
import org.springframework.context.ApplicationContext;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class GetFlowRecordContextListFlow implements BusinessFlow {
    @Override
    public void executeBusinessFlow(FlowContext flowContext) throws Exception {
        ApplicationContext applicationContext = flowContext.checkInstanceData(ApplicationContext.class);
        FlowMonitorOption flowMonitorOption = applicationContext.getBean(FlowMonitorOption.class);
        QuickAMSOption quickAMSOption = applicationContext.getBean(QuickAMSOption.class);
        List<String> categoryNameList = flowContext.getData("categoryNameList", List.class);

        List<FlowRecordContext> flowRecordContextList = new ArrayList<>();
        List<FlowRecordable> flowRecordableList = QueryPackage.newQuery(flowMonitorOption.basePackageName)
                .addClassQuery(FlowRecordable.class)
                .execute()
                .getInstanceList(FlowRecordable.class);
        if(null==flowRecordableList||flowRecordableList.isEmpty()){
            return;
        }
        for(FlowRecordable flowRecordable:flowRecordableList){
            try {
                FlowRecordContext flowRecordContext = new FlowRecordContext();
                flowRecordContext.name = flowRecordable.name();
                flowRecordContext.categoryName = "其他";
                flowRecordContext.flowRecordable = flowRecordable;

                for(Map.Entry<String,String> entry:quickAMSOption.packageNameLabelMap.entrySet()){
                    String className = flowRecordable.getClass().getName();
                    if(className.contains(entry.getKey())){
                        flowRecordContext.categoryName = entry.getValue();
                    }
                }
                if(null!=categoryNameList&&!categoryNameList.contains(flowRecordContext.categoryName)){
                    continue;
                }

                flowRecordContextList.add(flowRecordContext);
            }catch (Exception e){
                throw new RuntimeException(e);
            }
        }
        flowContext.putReturnData("list", flowRecordContextList);
    }

    @Override
    public String name() {
        return "获取流程记录上下文记录列表";
    }
}
